"""
------------
Created by Wenyi Wang

10/29/2014

Modified by Dan Pinolini around Xmas 2015
Runs on Python 2.0
Optimized to limit NN in calculation

Modified by Wenyi
2/17/2015
Runs on Python 3.0
BUGS REMOVED: NN no longer has duplicates

Modified by Marlene 2/25/2015
Runs on Python 3.0
Bugs removed: NNLimit converted in int
------------

Purpose:

Read files from BioSim (BioSim.txt, BioSim_Conf.txt)
For each compound, find it's biological neighbors according to the user defined cutoff
And sort the neighbors by biosimilarity

Output should be:

comp1   nn1  nn2  nn3  
comp2   nn1
comp3   nn1  nn2  nn3  nn4  nn5  nn6
...

*Problem:0

Avoid applying on big database (e.g. number of compounds > 5,000)


"""

print("------Bio Neighbors Finder------\n")
print("Read files from BioSim (BioSim.txt, BioSim_Conf.txt)\n")
print('''For each compound, I find biological neighbors according to the user defined cutoffs
And sort the neighbors by biosimilarity

*Problem: I take up lots of memory.
          Please avoid applying on huge database (e.g. number of compounds > 5,000)

------------
''')
useConf=input("Please Enter the smallest confidence you would like to regard: ")
#print("Got it, thx!\n")
useConf=float(useConf)


biosim=open('BioSim.txt','r')
conf=open('BioSim_Conf.txt','r')
title=biosim.readline().strip()
conf.readline()

from operator import itemgetter, attrgetter, methodcaller

nb = open('New_Bio_sim_file.txt','w')
from time import gmtime, strftime
nb.write(title)
nb.write('\n')
for line in biosim:
    sim = line.strip().split()
    cf = conf.readline().strip().split()
    nb.write(sim[0] + '\t')
    for i in range(1, len(sim)):
        if sim[i] == 'N' or float(cf[i]) > useConf:
            nb.write(sim[i] + '\t')
        else:
            nb.write("-2" + '\t')
    nb.write('\n')

biosim.close()
conf.close()
nb.close()
'''
    d = []
    nb.write(sim[0]+'\t')

    for i in range(1,len(sim)):
        if sim[0] != title[i] and sim[i] != 'N':
            if  float(cf[i]) <= useConf:
                d.append((title[i], sim[i], cf[i]))

    d.sort(key=itemgetter(1,2,0),reverse=True)

    count = 0
    for e in d:
        try:
            if count >= NNLimit:
                break
        except NameError:
            pass
        if float(e[1]) <= cutoff and float(e[2]) >= useConf:
            nb.write(e[0]+'\t')
            count+=1

##    for e in d:
##        if count >= NNLimit:
##            break
##        if e[1] >= cutoff and e[2] >= useConf:
##            nb.write(e[0]+'\t')
##            count+=1

title=biosim.readline().strip().split()
conf.readline()
'''